package com.study.cloud.config.nacos.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.listener.Listener;
import com.alibaba.nacos.api.exception.NacosException;
import com.study.cloud.config.api.ConfigCenter;
import com.study.cloud.config.api.RuleChangeListener;
import com.study.cloud.gateway.common.rule.Rule;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.Executor;

/**
 * @author wangwancheng
 * @create 2025/7/19 20:44
 */
@Slf4j
public class NacosConfigCenter implements ConfigCenter {

    private static final String DATA_ID = "api-gateway";

    private String serverAddress;

    private String env;
    //nacos ConfigService
    private ConfigService configService;
    @Override
    public void init(String registerAddress, String env) {
        this.serverAddress = registerAddress;
        this.env = env;
        try {
            this.configService = NacosFactory.createConfigService(serverAddress);
        } catch (NacosException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void subscribeRuleChange(RuleChangeListener listener) {

        try {
            //获取配置
            String config = configService.getConfig(DATA_ID,env, 5000);
            //{"rules":[{},{}]}
            log.info("nacos获取配置成功：{}",config);
            listener.onRuleChange(JSON.parseObject(config).getJSONArray("rules").toJavaList(Rule.class));
            //监听变化
            configService.addListener(DATA_ID, env, new Listener() {
                @Override
                public Executor getExecutor() {
                    return null;
                }

                /**
                 * 变更时通知
                 * @param s
                 */
                @Override
                public void receiveConfigInfo(String s) {
                    log.info("config from nacos: {}", s);
                    listener.onRuleChange(JSON.parseObject(s).getJSONArray("rules").toJavaList(Rule.class));
                }
            });
        } catch (NacosException e) {
            throw new RuntimeException(e);
        }

    }
}
